#pragma once

#include <iostream>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/daily_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>

class LoggerManager {
public:

    struct LoggerConfig {
        std::string log_path;
        int max_files;
        spdlog::level::level_enum log_level;
        int rotation_hour;//重置时间
        int rotation_minute;

        LoggerConfig() : log_path("logs/log"), max_files(7), 
            log_level(spdlog::level::info), rotation_hour(0), 
            rotation_minute(0) { }
    };


    static std::shared_ptr<spdlog::logger> init(const LoggerConfig& config = LoggerConfig()) {
        try {
            auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
            console_sink->set_level(config.log_level);
            console_sink->set_pattern(R"(%^%L%$ | %Y-%m-%dT%H:%M:%S.%e | %t | %s:%# | %v)");

            auto file_sink = std::make_shared<spdlog::sinks::daily_file_sink_mt>(
                config.log_path + ".log", 
                config.rotation_hour, 
                config.rotation_minute, 
                false, 
                config.max_files
            );
            file_sink->set_level(config.log_level);
            file_sink->set_pattern(R"(%^%L%$ | %Y-%m-%dT%H:%M:%S.%e | %t | %s:%# | %v)");

            std::vector<spdlog::sink_ptr> sinks{console_sink, file_sink};
            auto logger = std::make_shared<spdlog::logger>(
                "multi_sink", 
                sinks.begin(), 
                sinks.end()
            );

            logger->set_level(config.log_level);

            // 立即刷新
            logger->flush_on(spdlog::level::warn);

            spdlog::register_logger(logger);
            spdlog::set_default_logger(logger);

            // 异常处理
            spdlog::set_error_handler([](const std::string& msg) {
                std::cerr << "Logger error: " << msg << std::endl;
            });

            return logger;
        }
        catch (const spdlog::spdlog_ex& ex) {
            std::cerr << "Log initialization failed: " << ex.what() << std::endl;
            return nullptr;
        }
    }

    // 关闭日志
    static void shutdown() {
        spdlog::shutdown();
    }

    // 获取当前日志级别
    static spdlog::level::level_enum get_level() {
        return spdlog::default_logger()->level();
    }

    // 禁止实例化
    LoggerManager() = delete;
    ~LoggerManager() = delete;
};

#define logt(...) SPDLOG_TRACE(__VA_ARGS__)
#define logd(...) SPDLOG_DEBUG(__VA_ARGS__)
#define logi(...) SPDLOG_INFO(__VA_ARGS__)
#define logw(...) SPDLOG_WARN(__VA_ARGS__)
#define loge(...) SPDLOG_ERROR(__VA_ARGS__)
#define logc(...) SPDLOG_CRITICAL(__VA_ARGS__)
